const { json } = require("express");
const { sqlPromise } = require("../db/sqlPromise");
const turnTree = require("../util/turnTree");

exports.getRoles = async (req, res) => {
  let sql1 =
    "select role_id as id, role_name as roleName, role_desc as roleDesc, ps_ids as children from sp_role";
  //   select articles.id, articles.title, articles.pub_date, articles.state,cate.name as cate_name
  //   from ev_articles articles left join ev_article_cate cate on cate.id=articles.cate_id where articles.is_delete=0
  let res1 = await sqlPromise(sql1, [req.body.username]);

  let sql2 =
    "select ps_id as id, ps_name as authName, ps_level as level, ps_pid as pid from sp_permission";
  let res2 = await sqlPromise(sql2);

  for (let i = 0; i < res1.length; i++) {
    let child = res1[i].children;
    //第一次处理 将ps_ids 转换为 list形式的权限
    // children: '101,0,104,105,116,117,115,142,143,144,121,122,123,149,103,111,129,134,138,112,147'
    res1[i].children = res2.filter((item, index) => {
      if (child.indexOf(item.pid) != -1) return true;
    });
    // if (i === 0) console.log(res1[i].children);

    //第二次处理 turnTree
    res1[i].children = turnTree(res1[i].children);
  }
  res.send({
    data: res1,
    meta: {
      msg: "获取成功",
      status: 200,
    },
  });
};

exports.addRoles = async (req, res) => {
  let sql = "select * from sp_role where role_name=?";
  let result1 = await sqlPromise(sql, [req.body.roleName]);
  if (result1.length > 0) return res.send({ status: 100, msg: "角色已存在" });

  let str1 = "role_name";
  let str2 = "?";
  if (req.body.roleDesc) {
    str1 = "role_name,role_Desc";
    str2 = "?,?";
  }

  let insertSql = `insert into sp_role (${str1}) values (${str2})`;
  let result2 = await sqlPromise(insertSql, [
    req.body.roleName,
    req.body.roleDesc,
  ]);
  if (result2.affectedRows != 1)
    return res.send({ status: 100, msg: "角色添加失败" });

  let result3 = await sqlPromise(sql, [req.body.roleName]);
  console.log(result3);
  res.send({
    data: {
      roleId: result3[0].role_id,
      roleName: result3[0].role_name,
      roleDesc: result3[0].role_desc,
    },
    meta: {
      msg: "创建成功",
      status: 201,
    },
  });
};

exports.getRole = async (req, res) => {
  let id = req.params.id;
  let sql = "select * from sp_role where role_id=?";
  let result = await sqlPromise(sql, [id]);
  if (!result.length) return res.send({ status: 100, msg: "查找失败" });

  res.send({
    data: {
      roleId: result[0].role_id,
      roleName: result[0].role_name,
      roleDesc: result[0].role_desc,
    },
    meta: {
      msg: "查找成功",
      status: 200,
    },
  });
};

exports.editRole = async (req, res) => {
  let id = req.params.id;
  let sql = "select * from sp_role where role_id=?";
  let result = await sqlPromise(sql, [id]);
  if (!result.length) return res.send({ status: 100, msg: "此id不存在" });

  let str1 = `role_name = '${req.query.roleName}'`;
  if (req.query.roleDesc) {
    str1 = `role_name = '${req.query.roleName}',role_Desc= '${req.query.roleDesc}'`;
  }

  let updateSql = `UPDATE sp_role SET ${str1} WHERE role_id=${req.params.id}`;
  let upResult = await sqlPromise(updateSql);
  if (upResult.affectedRows != 1)
    return res.send({ status: 100, msg: "角色编辑失败" });

  let endResult = await sqlPromise(sql, [id]);

  res.send({
    data: {
      roleId: endResult[0].role_id,
      roleName: endResult[0].role_name,
      roleDesc: endResult[0].role_desc,
    },
    meta: {
      msg: "角色编辑成功",
      status: 200,
    },
  });
};

exports.delRole = async (req, res) => {
  let sql = "DELETE FROM sp_role WHERE role_id = ?";
  let results = await sqlPromise(sql, [req.params.id]);
  if (results.affectedRows != 1)
    return res.send({
      msg: "删除失败",
      status: 100,
    });

  res.send({
    data: null,
    meta: {
      msg: "删除成功",
      status: 200,
    },
  });
};

exports.addRight = async (req, res) => {
  let roleId = req.params.roleId;
  let rightId = req.query.rightId;
  let sql1 = "select ps_ids from sp_role where role_id=?";
  let result1 = await sqlPromise(sql1, [roleId]);
  let newRight = [
    ...new Set([...result1[0].ps_ids.split(","), ...rightId.split(",")]),
  ];
  console.log(newRight);

  let sql2 = `UPDATE sp_role SET ps_ids = ? WHERE role_id=${roleId}`;
  let result2 = await sqlPromise(sql2, [newRight.join(",")]);

  if (result2.affectedRows == 0)
    return res.send({
      msg: "授权失败",
      status: 100,
    });

    //获取所有权限信息
  let sql3 =
    "select ps_id as id, ps_name as authName, ps_level as level, ps_pid as pid from sp_permission";
  let result3 = await sqlPromise(sql3);

    let newTree = []
    for(let i =0;i<result3.length;i++) {
      if( newRight.indexOf(result3[i].id.toString()) != -1) newTree.push(result3[i])
    }

    newTree = turnTree(newTree);

  res.send({
    data: newTree,
    meta: {
      msg: "授权成功",
      status: 200,
    },
  });
};

exports.delRight = async (req, res) => {
  let roleId = req.params.roleId;
  let rightId = req.params.rightId;
  let sql1 = "select ps_ids from sp_role where role_id=?";
  let result1 = await sqlPromise(sql1, [roleId]);

  let ps_ids = result1[0].ps_ids.split(",");
  if (!ps_ids.includes(rightId))
    return res.send({ meta: { msg: "该权限不存在", status: 200 } });

  newIds = ps_ids.reduce((pre, cur) => {
    if (cur == rightId) {
      return pre;
    } else {
      return pre == "" ? cur : pre + "," + cur;
    }
  }, "");

  let sql2 = `UPDATE sp_role SET ps_ids = ? WHERE role_id=${roleId}`;
  let result2 = await sqlPromise(sql2, [newIds]);

  res.send({
    data: null,
    meta: {
      msg: "角色Id删除 " + newIds,
      status: 200,
    },
  });
};
